﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Script
{
    class GameOverTwoPanel:UIBase
    {
        public List<SortNumIconSprite> sortNumIconSprites = new List<SortNumIconSprite>();
        public Button lastBtn;
        public Text thText, levelText;
        public override void Init()
        {
            base.Init();
            MessageCenter.Ins.ListenMess<Dictionary<string, PlayerData>>(MessId.RefureRankingList, RefureRankingList);
            lastBtn.onClick.AddListener(() =>
            {
                UIManager.Ins.OpenUI(UIName.GameOverThreePanel);
                UIManager.Ins.CloseUI(UIName.GameOverTwoPanel);
                Time.timeScale = 1;
            });
        }

        private void RefureRankingList(Dictionary<string, PlayerData> dic)
        {
            thText.text = PlayerPrefs.GetInt("PlayerTH") + "th";
            levelText.text = PlayerPrefs.GetInt("PlayerLevel").ToString();
            List<PlayerData> list = new List<PlayerData>();
            foreach (var item in dic)
            {
                list.Add(item.Value);
            }
            list.Sort((a, b) =>
            {
                if (a.nowLevel > b.nowLevel)
                {
                    return -1;
                }
                else if (a.nowLevel < b.nowLevel)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            });
            for (int i = 0; i < sortNumIconSprites.Count ; i++)
            {
                if (i < list.Count)
                {
                    sortNumIconSprites[i].GetComponent<SortNumIconSprite>().SetName(list[i].name);
                    sortNumIconSprites[i].GetComponent<SortNumIconSprite>().SetLevel(list[i].nowLevel,100-i);
                }
            }
            for (int i = 6; i < list.Count; i++)
            {
                if (list[i].name == "player")
                {
                    sortNumIconSprites[6].GetComponent<SortNumIconSprite>().SetName(list[i].name);
                    sortNumIconSprites[6].GetComponent<SortNumIconSprite>().SetLevel(list[i].nowLevel,100-i);
                    sortNumIconSprites[6].GetComponent<SortNumIconSprite>().SetNum(i + 1);
                    return;
                }
            }
        }
    }
}
